module tri_gen (
    clk,
    res,
    d_out
);
input       clk;
input       res;
output[8:0] d_out;

reg[1:0] state;//状态机寄存器
reg[8:0] d_out;
reg[7:0] cont;

always @(posedge clk or res) begin
    if (res==0) begin
        state<=0;
        d_out<=0;  
        cont<=0;   
    end else begin
        case (state)
            0://上
                begin
                    d_out<=d_out+1;
                    if (d_out==299) begin
                        state<=2;
                    end
                end
            1: //下
                begin
                    d_out<=d_out-1;
                    if (d_out==1) begin
                        state<=0; 
                    end
                end
            2://平
                begin
                    
                    if (cont==200) begin
                        state<=1;
                        cont<=0;
                    end else begin
                        cont<=cont+1;
                    end
                end
        endcase
    end

end
    
endmodule

`timescale 1ns/10ps
module tri_gen_tb ();

reg clk;
reg res;
wire [8:0] d_out;

tri_gen T1 (
    .clk(clk),
    .res(res),
    .d_out(d_out)
);

initial begin
            clk<=0; res<=0;
    #17     res<=1;
    #100000 $stop;
end

always #5 clk=~clk;
    
endmodule
